import React, { useState, useRef, useEffect } from 'react';
import { StyleSheet, Text, View, Modal, PanResponder, Dimensions, Image } from 'react-native';
import { connect } from 'react-redux'
import { pTx } from "../utils/dimensions"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../realm"
import Realm from "realm"
import IconFont from '@pingtou/rn-vant-icons'
import AudioRecorderPlayer from 'react-native-audio-recorder-player';
import httpApi from "../api"
const audioRecorderPlayer = new AudioRecorderPlayer();
var _pollingInterval = null
var _modalVisible = false
const VoicePressable = (props) => {
    console.log(props.route.params)
    const realm = useRealm();
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const [modalVisible, setModalVisible] = useState(false);
    const [cancelOrConfirm, setCancelOrConfirm] = useState(true);
    const [recordSecs, setRecordSecs] = useState(0);
    const [recordTime, setRecordTime] = useState(null);
    var _cancelOrConfirm = true
    var height = Dimensions.get('screen').height - pTx(150)
    const panResponder = useRef(
        PanResponder.create({
            onMoveShouldSetPanResponder: () => true,
            onPanResponderGrant: () => {
                props.onStopPlayDebounce()
                setModalVisible(true)
                setCancelOrConfirm(true)
                _cancelOrConfirm = true
                _modalVisible = true

            },
            onPanResponderMove: ({ nativeEvent }, gestureState) => {
                const nextImage = Math.round(nativeEvent.pageY)
                if ((_cancelOrConfirm && nextImage < height) || (!_cancelOrConfirm && nextImage >= height)) {
                    _cancelOrConfirm = _cancelOrConfirm ? false : true
                    setCancelOrConfirm(_cancelOrConfirm)
                }
            },
            onPanResponderRelease: async () => {
                setModalVisible(false)
                _modalVisible = false
            }
        })
    ).current;

    useEffect(() => {
        setRecordSecs(0)
        if (modalVisible) {
            _pollingInterval = setInterval(() => {
                clearInterval(_pollingInterval);
                _pollingInterval = null
                const result = audioRecorderPlayer.startRecorder().then(() => {
                    audioRecorderPlayer.addRecordBackListener((e) => {
                        setRecordSecs(e.currentPosition)
                        setRecordTime(audioRecorderPlayer.mmssss(
                            Math.floor(e.currentPosition),
                        ))
                        if (e.currentPosition >= 60000) {
                            setModalVisible(false)
                            setCancelOrConfirm(true)
                        }
                        if (!_modalVisible && e.currentPosition >= 800) {
                            audioRecorderPlayer.stopRecorder()
                            audioRecorderPlayer.removeRecordBackListener();
                        }
                        return;
                    });
                })
            }, 200)
        } else {
            clearInterval(_pollingInterval);
            _pollingInterval = null
            if (recordSecs > 800 && cancelOrConfirm) {
                audioRecorderPlayer.stopRecorder().then(async (uri) => {
                    try {
                        const upload = await httpApi.uploadMinio({
                            uri,
                            name: "sound.mp4",
                            type: "video/mp4",
                        })
                        console.log(upload)
                        var timestamp = Date.parse(new Date()) / 1000
                        let uuidv4Id = new Realm.BSON.UUID()
                        const realmItem = {
                            G: props.route.params.G,
                            F: props.route.params.F,
                            M: recordSecs + " " + upload.data.FileNames[0] + " " + "sound.mp4",
                            MT: 5,
                            S: -1,
                            T: timestamp,
                            _id: uuidv4Id,
                            Unread: 0,
                            UserId: userInfo.Id
                        }
                        if (realmItem.G) {
                            realm.write(() => {
                                realm.create(schemaName.GroupMsgLis, realmItem, true);
                            })
                            const res = await httpApi.sendGroupFile({
                                groupId: realmItem.G,
                                msgType: 5,
                                srcFileName: upload.data.FileNames[0],
                                dstFileName: upload.data.FileNames[0],
                                fileSize: recordSecs
                            })
                            realm.write(() => {
                                realm.create(schemaName.GroupMsgLis, {
                                    _id: uuidv4Id,
                                    SendState: 1,
                                }, true);
                            })
                        } else {
                            realm.write(() => {
                                console.log("1111111111111111111")
                                realm.create(schemaName.FriendMsgLis, realmItem, true);
                                console.log("222222222222222222")

                            })
                            const res = await httpApi.sendFriendFile({
                                id: props.route.params.F,
                                msgType: 5,
                                srcFileName: upload.data.FileNames[0],
                                dstFileName: upload.data.FileNames[0],
                                fileSize: recordSecs
                            })
                            if (res.code != 20) {
                                realm.write(() => {
                                    realm.create(schemaName.FriendMsgLis, {
                                        _id: uuidv4Id,
                                        SendState: 2,
                                    }, true);
                                })
                            }

                        }

                    }
                    catch (error) {
                        console.log(error, "!122")
                    }
                    audioRecorderPlayer.removeRecordBackListener();
                })
            }


        }
    }, [modalVisible])

    return (
        <>
            <Text {...panResponder.panHandlers} style={styles.send}>按住 说话</Text>
            <Modal
                animationType="fade"
                transparent={true}
                visible={modalVisible}
                onRequestClose={() => {
                    setModalVisible(!modalVisible);
                }}
            >
                <View style={styles.centeredView}>
                    <View style={styles.modalView}>
                        <View style={[styles.sponderImage, { backgroundColor: cancelOrConfirm ? "#06C161" : "#F35E4D" }]}>
                            <Image style={{ width: pTx(60), height: pTx(30) }} source={require('../assets/image/player.gif')}></Image>
                            <IconFont name="play" color={cancelOrConfirm ? "#06C161" : "#F35E4D"} size={pTx(25)} style={[styles.triangle]} />
                        </View>
                        <Text style={styles.modalText}>{cancelOrConfirm ? "松开发送" : "松开取消"}</Text>
                    </View>
                </View>
            </Modal>
        </>
    );
};

const mapStateToProps = (state) => state.app

const mapDispatchToProps = {
}

export default connect(mapStateToProps, mapDispatchToProps)(VoicePressable)


const styles = StyleSheet.create({
    send: {
        flex: 1,
        paddingVertical: 0,
        minHeight: pTx(40),
        textAlign: "center",
        textAlignVertical: "center",
        fontSize: pTx(16),
        color: "#000",
        backgroundColor: "#fff",
        borderRadius: pTx(4),
    },
    centeredView: {
        flex: 1,
        position: "relative",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "flex-end",
        backgroundColor: "rgba(0,0,0,0.5)"
    },
    modalView: {
        position: "absolute",
        bottom: -pTx(125),
        width: pTx(500),
        height: pTx(250),
        flexDirection: "row",
        justifyContent: "center",
        borderTopEndRadius: pTx(250),
        borderTopLeftRadius: pTx(250),
        backgroundColor: "#EDEDED"
    },
    sponderImage: {
        position: "absolute",
        top: -pTx(150),
        width: pTx(180),
        height: pTx(50),
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "#06C161",
        borderRadius: pTx(6),
        zIndex: 9,
    },
    triangle: {
        position: "absolute",
        bottom: -pTx(15),
        fontSize: pTx(40),
        transform: [{ rotate: "90deg" }]
    },
    modalText: {
        position: "absolute",
        top: -pTx(30),
        fontSize: pTx(14),
        color: "#EDEDED",
        textAlign: "center"
    },
});

